package za.ac.wits.elen7045.persistence.model;

import java.util.LinkedList;
import java.util.List;
import za.ac.wits.elen7045.persistence.PersistentObject;
import za.ac.wits.elen7045.persistence.exception.ObjectAlreadyExistException;
import za.ac.wits.elen7045.persistence.exception.ObjectNotFoundException;
import za.ac.wits.elen7045.persistence.util.ValidationUtilities;

public class ServiceProvider extends PersistentObject {

	private ServiceProviderName serviceProviderType;
	private String name;
	private String url;
	private List<Credential> requiredCredentials;
	
	public ServiceProvider(ServiceProviderName serviceProviderType, String name) {
		this.serviceProviderType = serviceProviderType;
		this.name = name;
	}
	
	public AccountType getAccountType() {
		return serviceProviderType.getAccountType();
	}
	
	public ServiceProviderName getServiceProviderType() {
		return serviceProviderType;
	}
	
	public String getName() {
		return name;
	}

	public String getUrl() {
		return url;
	}
	
	public void setUrl(String url) {
		this.url = url;
	}
	
	public List<Credential> getRequiredCredentials() {
		return requiredCredentials;
	}
	
	public void setRequiredCredentials(List<Credential> requiredCredentials) {
		List<Credential> credentials = new LinkedList<Credential>();
		for (Credential credential : requiredCredentials) {
			credentials.add(new Credential(credential.getName()));
		}
		this.requiredCredentials = credentials;
	}
	
	public Credential getRequiredCredential(String name) {
		for (Credential credential : requiredCredentials) {
			if (ValidationUtilities.isEqual(credential.getName(), name)) {
				return credential;
			}
		}
		return null;
	}
	
	public void addRequiredCredential(String name) {
		if (getRequiredCredential(name) != null) {
			throw new ObjectAlreadyExistException();
		} else {
			requiredCredentials.add(new Credential(name, null, false));
		}
	}
	
	public void removeRequiredCredential(String name) {
		Credential persistedCredential = null;
		for (Credential credential : requiredCredentials) {
			if (ValidationUtilities.isEqual(credential.getName(), name)) {
				persistedCredential = credential;
				break;
			}
		}
		if (persistedCredential != null) {
			requiredCredentials.remove(persistedCredential);
		} else {
			throw new ObjectNotFoundException();
		}				
	}
	
}
